package com.itheima.behaviour.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.behaviour.dto.LikesBehaviourDto;
import com.itheima.behaviour.feign.ApBehaviourEntryFeign;
import com.itheima.behaviour.pojo.ApBehaviorEntry;
import com.itheima.behaviour.pojo.ApLikesBehavior;
import com.itheima.behaviour.mapper.ApLikesBehaviorMapper;
import com.itheima.behaviour.service.ApLikesBehaviorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.pojo.Result;
import com.itheima.common.util.RequestContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 * APP点赞行为表 服务实现类
 * </p>
 *
 * @author 作者
 * @since 2021-08-30
 */
@Service
public class ApLikesBehaviorServiceImpl extends ServiceImpl<ApLikesBehaviorMapper, ApLikesBehavior> implements ApLikesBehaviorService {

    @Autowired
    private ApLikesBehaviorMapper apLikesBehaviorMapper;

    @Autowired
    private ApBehaviourEntryFeign apBehaviourEntryFeign;

    /**
     * 点赞/取消点赞行为记录
     * @param dto
     */
    @Override
    public void like(LikesBehaviourDto dto) {
        //判断当前操作是机器还是会员用户
        Integer id = RequestContext.getNodeValue("id");
        Result<ApBehaviorEntry> entryResult = apBehaviourEntryFeign.getByEquipmentIdOrUserId(dto.getEquipmentId(), id);
        ApBehaviorEntry entry = entryResult.getData();

        //1:点赞
        //1.1:查询该用户是否已经点赞过->查询出来
        QueryWrapper<ApLikesBehavior> apLikesBehaviorQueryWrapper = new QueryWrapper<ApLikesBehavior>();
        apLikesBehaviorQueryWrapper.eq("entry_id",entry.getId());
        apLikesBehaviorQueryWrapper.eq("article_id",dto.getArticleId());
        ApLikesBehavior apLikesBehavior = apLikesBehaviorMapper.selectOne(apLikesBehaviorQueryWrapper);

        //1.2:增加点赞记录
        if(dto.getOperation()==0 && apLikesBehavior==null){
            apLikesBehavior = new ApLikesBehavior();
            apLikesBehavior.setEntryId(entry.getId());
            apLikesBehavior.setArticleId(dto.getArticleId());
            apLikesBehavior.setType(dto.getType());
            apLikesBehavior.setOperation(dto.getOperation());
            apLikesBehavior.setCreatedTime(LocalDateTime.now());
            apLikesBehaviorMapper.insert(apLikesBehavior);
        }else {
            //2:取消点赞
            //2.1:查询出点赞对象
            apLikesBehavior.setOperation(dto.getOperation());
            //2.2:修改状态
            apLikesBehaviorMapper.updateById(apLikesBehavior);
        }
    }
}
